<template>
  <!-- 作业发布容器 -->
  <div class="task-upload-container">
    <h3>发布作业</h3>

    <!-- 表单区域 -->
    <el-form :model="formData" label-width="70px" >
      <!-- 使用 el-row 和 el-col 进行网格布局 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <!-- 题目名称输入 -->
          <el-form-item label="题目名称">
            <el-input v-model="formData.taskName" placeholder="请输入题目名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <!-- 题目描述输入 -->
          <el-form-item label="题目描述">
            <el-input
                v-model="formData.taskDesc"
                type="textarea"
                :rows="3"
                placeholder="请输入题目描述"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <!-- 选择按钮组 -->
          <div class="selection-buttons">
            <el-button type="primary" @click="selectStudents">选择学生</el-button>
            <el-button type="primary" @click="selectClass">选择班级</el-button>
            <el-button type="primary" @click="selectTeam">选择战队</el-button>
          </div>
        </el-col>
        <el-col :span="24">
          <!-- 文件上传区域 -->
          <el-upload
              ref="uploadRef"
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleFileChange"
              multiple
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到这里或<em>点击上传</em>
            </div>
          </el-upload>
        </el-col>
        <!-- 已选学生展示 -->
        <el-col :span="24" v-if="formData.selectedUsers.length > 0">
          <el-form-item label="已选学生">
            <el-tag
                v-for="student in selectedStudentsInfo"
                :key="student.userId"
                closable
                @close="removeSelectedStudent(student.userId)"
                class="selected-student-tag"
            >
              {{ student.nickname }} ({{ student.userName }})
            </el-tag>
          </el-form-item>
        </el-col>
        <!-- 已选班级展示 -->
        <el-col :span="24" v-if="formData.selectedClasses.length > 0">
          <el-form-item label="已选班级">
            <el-tag
                v-for="group in selectedClassesInfo"
                :key="group.groupId"
                closable
                @close="removeSelectedClass(group.groupId)"
                class="selected-group-tag"
            >
              {{ group.groupName }} (班级)
            </el-tag>
          </el-form-item>
        </el-col>
        <!-- 已选战队展示 -->
        <el-col :span="24" v-if="formData.selectedTeams.length > 0">
          <el-form-item label="已选战队">
            <el-tag
                v-for="group in selectedTeamsInfo"
                :key="group.groupId"
                closable
                @close="removeSelectedTeam(group.groupId)"
                class="selected-group-tag"
            >
              {{ group.groupName }} (战队)
            </el-tag>
          </el-form-item>
        </el-col>
        <!-- 提交按钮 -->
        <el-col :span="24">
          <el-button
              type="primary"
              @click="submitTask"
              :loading="isSubmitting"
          >
            提交作业
          </el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 学生选择弹窗 -->
    <el-dialog v-model="studentDialogVisible" title="选择学生" width="80%">
      <div class="student-cards">
        <!-- 学生卡片列表 -->
        <el-card
            v-for="student in students"
            :key="student.userId"
            class="student-card"
            :class="{ 'selected-card': isSelected(student.userId) }"
            @click="toggleStudentSelection(student.userId)"
        >
          <div class="student-info">
            <img :src="student.avatarUrl" alt="Avatar" class="avatar" />
            <div class="details">
              <p><strong>姓名:</strong> {{ student.nickname }}</p>
              <p><strong>用户名:</strong> {{ student.userName }}</p>
            </div>
          </div>
          <!-- 选中标记 -->
          <div class="selected-icon" v-if="isSelected(student.userId)">
            <i class="el-icon-check"></i>
          </div>
        </el-card>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelSelection">取消</el-button>
          <el-button type="primary" @click="confirmSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 班级选择弹窗 -->
    <el-dialog v-model="classDialogVisible" title="选择班级" width="80%">
      <div class="group-cards">
        <!-- 班级卡片列表 -->
        <el-card
            v-for="group in classes"
            :key="group.groupId"
            class="group-card"
            :class="{ 'selected-card': isClassSelected(group.groupId) }"
            @click="toggleClassSelection(group.groupId)"
        >
          <div class="group-info">
            <p><strong>班级名称:</strong> {{ group.groupName }}</p>
          </div>
          <!-- 选中标记 -->
          <div class="selected-icon" v-if="isClassSelected(group.groupId)">
            <i class="el-icon-check"></i>
          </div>
        </el-card>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelClassSelection">取消</el-button>
          <el-button type="primary" @click="confirmClassSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 战队选择弹窗 -->
    <el-dialog v-model="teamDialogVisible" title="选择战队" width="80%">
      <div class="group-cards">
        <!-- 战队卡片列表 -->
        <el-card
            v-for="group in teams"
            :key="group.groupId"
            class="group-card"
            :class="{ 'selected-card': isTeamSelected(group.groupId) }"
            @click="toggleTeamSelection(group.groupId)"
        >
          <div class="group-info">
            <p><strong>战队名称:</strong> {{ group.groupName }}</p>
          </div>
          <!-- 选中标记 -->
          <div class="selected-icon" v-if="isTeamSelected(group.groupId)">
            <i class="el-icon-check"></i>
          </div>
        </el-card>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelTeamSelection">取消</el-button>
          <el-button type="primary" @click="confirmTeamSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import TaskApi from '@/api/Task/TaskApi.ts';
import AllUserApi from '@/api/Backend/AllUserApi';
import GroupApi from '@/api/Backend/GroupApi.ts';
// 表单数据类型定义
interface FormData {
  taskName: string;        // 题目名称
  taskDesc: string;        // 题目描述
  selectedUsers: number[]; // 已选用户ID列表
  selectedClasses: number[]; // 已选班级ID列表
  selectedTeams: number[]; // 已选战队ID列表
  file?: File;             // 上传的文件
}
// 学生数据类型定义
interface Student {
  userId: number;     // 用户ID
  userName: string;   // 用户名
  nickname: string;   // 昵称
  avatarUrl: string;  // 头像URL
}
// 组数据类型定义(班级/战队)
interface Group {
  groupId: number;    // 组ID
  groupName: string;  // 组名称
  groupType: string;  // 组类型(班级/战队)
}
// 表单数据响应式对象
const formData = ref<FormData>({
  taskName: '',
  taskDesc: '',
  selectedUsers: [],
  selectedClasses: [],
  selectedTeams: []
});
const uploadRef = ref();
// 提交状态
const isSubmitting = ref(false);
// 上传文件
const uploadFile = ref<File | null>(null);
// 学生选择弹窗显示状态
const studentDialogVisible = ref(false);
// 学生列表
const students = ref<Student[]>([]);
// 临时选中的学生ID列表
const tempSelectedUsers = ref<number[]>([]);
// 班级选择弹窗显示状态
const classDialogVisible = ref(false);
// 战队选择弹窗显示状态
const teamDialogVisible = ref(false);
// 班级列表
const classes = ref<Group[]>([]);
// 战队列表
const teams = ref<Group[]>([]);
// 临时选中的班级ID列表
const tempSelectedClass = ref<number[]>([]);
// 临时选中的战队ID列表
const tempSelectedTeam = ref<number[]>([]);
/**
 * 获取已选班级的详细信息
 * @returns 已选班级信息列表
 */
const selectedClassesInfo = computed(() => {
  return classes.value.filter(group =>
      formData.value.selectedClasses.includes(group.groupId)
  );
});
/**
 * 获取已选战队的详细信息
 * @returns 已选战队信息列表
 */
const selectedTeamsInfo = computed(() => {
  return teams.value.filter(group =>
      formData.value.selectedTeams.includes(group.groupId)
  );
});
/**
 * 获取已选学生的详细信息
 * @returns 已选学生信息列表
 */
const selectedStudentsInfo = computed(() => {
  return students.value.filter(student =>
      formData.value.selectedUsers.includes(student.userId)
  );
});
/**
 * 处理文件变化事件
 * @param file 上传的文件
 */
const handleFileChange = (file: any) => {
  // 确保 file.raw 是一个 File 对象
  if (file.raw instanceof File) {
    uploadFile.value = file.raw;
    console.log('uploadFile.value:', uploadFile.value);
  } else {
    console.error('Invalid file object:', file.raw);
  }
};
/**
 * 选择学生按钮点击事件
 */
const selectStudents = async () => {
  await fetchStudents();
  tempSelectedUsers.value = [...formData.value.selectedUsers]; // 初始化临时选择
  studentDialogVisible.value = true;
};
/**
 * 选择班级按钮点击事件
 */
const selectClass = async () => {
  const groups = await fetchGroups();
  classes.value = groups.filter(group => group.groupType === '班级');
  tempSelectedClass.value = [];
  classDialogVisible.value = true;
};
/**
 * 选择战队按钮点击事件
 */
const selectTeam = async () => {
  const groups = await fetchGroups();
  teams.value = groups.filter(group => group.groupType === '战队');
  tempSelectedTeam.value = [];
  teamDialogVisible.value = true;
};
/**
 * 提交作业
 */
const submitTask = async () => {
  // 验证题目名称
  if (!formData.value.taskName) {
    ElMessage.warning('请输入题目名称');
    return;
  }

  // 验证文件
  if (!uploadFile.value) {
    ElMessage.warning('请上传作业文件');
    return;
  }

  // 验证至少选择了一种方式（学生/班级/战队）
  if (
      formData.value.selectedUsers.length === 0 &&
      formData.value.selectedClasses.length === 0 &&
      formData.value.selectedTeams.length === 0
  ) {
    ElMessage.warning('请选择至少一个学生、班级或战队');
    return;
  }

  try {
    isSubmitting.value = true;

    // 构建提交数据
    const dto = {
      vaTask: {
        taskName: formData.value.taskName,
        taskDesc: formData.value.taskDesc
      },
      userIds: formData.value.selectedUsers
    };

    // 调用API提交作业
    const response = await TaskApi.addVaTask({
      dto: dto,
      file: uploadFile.value
    });

    if (response.code === 200) {
      ElMessage.success('作业发布成功');

      // 完全重置表单
      resetForm();
    } else {
      ElMessage.error(response.msg || '作业发布失败');
    }
  } catch (error) {
    console.error('提交作业失败', error);
    ElMessage.error('作业发布失败');
  } finally {
    isSubmitting.value = false;
  }
};

// 添加resetForm方法
const resetForm = () => {
  formData.value = {
    taskName: '',
    taskDesc: '',
    selectedUsers: [],
    selectedClasses: [],
    selectedTeams: []
  };
  uploadFile.value = null;
  // 同时清空临时选择
  tempSelectedUsers.value = [];
  tempSelectedClass.value = [];
  tempSelectedTeam.value = [];
  // 清空文件上传组件
  uploadRef.value?.clearFiles();
};

/**
 * 获取学生列表
 */
const fetchStudents = async () => {
  try {
    const response = await AllUserApi.getAllStudent();
    if (response.code === 200) {
      students.value = response.data;
    }
  } catch (error) {
    console.error('获取学生列表失败', error);
    ElMessage.error('获取学生列表失败');
  }
};
/**
 * 获取组列表(班级/战队)
 * @returns 组列表
 */
const fetchGroups = async () => {
  try {
    const response = await GroupApi.getGroup();
    if (response.code === 200) {
      return response.data;
    }
  } catch (error) {
    console.error('获取组列表失败', error);
    ElMessage.error('获取组列表失败');
  }
  return [];
};
/**
 * 切换学生选择状态
 * @param studentId 学生ID
 */
const toggleStudentSelection = (studentId: number) => {
  const index = tempSelectedUsers.value.indexOf(studentId);
  if (index === -1) {
    tempSelectedUsers.value.push(studentId);
  } else {
    tempSelectedUsers.value.splice(index, 1);
  }
};
/**
 * 检查学生是否被选中
 * @param studentId 学生ID
 * @returns 是否选中
 */
const isSelected = (studentId: number) => {
  return tempSelectedUsers.value.includes(studentId);
};
/**
 * 确认学生选择
 */
const confirmSelection = () => {
  formData.value.selectedUsers = [...tempSelectedUsers.value];
  studentDialogVisible.value = false;
};
/**
 * 取消学生选择
 */
const cancelSelection = () => {
  tempSelectedUsers.value = [...formData.value.selectedUsers];
  studentDialogVisible.value = false;
};
/**
 * 移除已选学生
 * @param userId 用户ID
 */
const removeSelectedStudent = (userId: number) => {
  const index = formData.value.selectedUsers.indexOf(userId);
  if (index !== -1) {
    formData.value.selectedUsers.splice(index, 1);
  }
};
/**
 * 检查班级是否被选中
 * @param groupId 班级ID
 * @returns 是否选中
 */
const isClassSelected = (groupId: number) => {
  return tempSelectedClass.value.includes(groupId);
};
/**
 * 切换班级选择状态
 * @param groupId 班级ID
 */
const toggleClassSelection = (groupId: number) => {
  const index = tempSelectedClass.value.indexOf(groupId);
  if (index === -1) {
    tempSelectedClass.value.push(groupId);
  } else {
    tempSelectedClass.value.splice(index, 1);
  }
};
/**
 * 确认班级选择
 */
const confirmClassSelection = async () => {
  const selectedClassIds = tempSelectedClass.value;
  const allUserIds = [];

  formData.value.selectedClasses = selectedClassIds; // 记录选中的班级ID

  // 获取每个班级的所有用户ID
  for (const classId of selectedClassIds) {
    const response = await GroupApi.getUsersByGroupId(classId);
    if (response.code === 200) {
      const users = response.data;
      users.forEach(user => {
        allUserIds.push(user.userId);
      });
    }
  }

  // 合并用户ID并去重
  formData.value.selectedUsers = [...new Set([...formData.value.selectedUsers, ...allUserIds])];
  classDialogVisible.value = false;
};

/**
 * 取消班级选择
 */
const cancelClassSelection = () => {
  tempSelectedClass.value = [];
  classDialogVisible.value = false;
};

/**
 * 检查战队是否被选中
 * @param groupId 战队ID
 * @returns 是否选中
 */
const isTeamSelected = (groupId: number) => {
  return tempSelectedTeam.value.includes(groupId);
};

/**
 * 切换战队选择状态
 * @param groupId 战队ID
 */
const toggleTeamSelection = (groupId: number) => {
  const index = tempSelectedTeam.value.indexOf(groupId);
  if (index === -1) {
    tempSelectedTeam.value.push(groupId);
  } else {
    tempSelectedTeam.value.splice(index, 1);
  }
};

/**
 * 确认战队选择
 */
const confirmTeamSelection = async () => {
  const selectedTeamIds = tempSelectedTeam.value;
  const allUserIds = [];

  formData.value.selectedTeams = selectedTeamIds; // 记录选中的战队ID

  // 获取每个战队的用户ID
  for (const teamId of selectedTeamIds) {
    const response = await GroupApi.getUsersByGroupId(teamId);
    if (response.code === 200) {
      const users = response.data;
      users.forEach(user => {
        allUserIds.push(user.userId);
      });
    }
  }

  // 合并用户ID并去重
  formData.value.selectedUsers = [...new Set([...formData.value.selectedUsers, ...allUserIds])];
  teamDialogVisible.value = false;
};

/**
 * 取消战队选择
 */
const cancelTeamSelection = () => {
  tempSelectedTeam.value = [];
  teamDialogVisible.value = false;
};

/**
 * 移除已选班级
 * @param groupId 班级ID
 */
const removeSelectedClass = (groupId: number) => {
  const index = formData.value.selectedClasses.indexOf(groupId);
  if (index !== -1) {
    formData.value.selectedClasses.splice(index, 1);
    // 同时移除该班级的所有用户
    const classUserIds = students.value
        .filter(student => student.groupId === groupId)
        .map(student => student.userId);
    formData.value.selectedUsers = formData.value.selectedUsers.filter(
        userId => !classUserIds.includes(userId)
    );
  }
};

/**
 * 移除已选战队
 * @param groupId 战队ID
 */
const removeSelectedTeam = (groupId: number) => {
  const index = formData.value.selectedTeams.indexOf(groupId);
  if (index !== -1) {
    formData.value.selectedTeams.splice(index, 1);
    // 同时移除该战队的所有用户
    const teamUserIds = students.value
        .filter(student => student.groupId === groupId)
        .map(student => student.userId);
    formData.value.selectedUsers = formData.value.selectedUsers.filter(
        userId => !teamUserIds.includes(userId)
    );
  }
};

// 组件挂载时获取学生列表
onMounted(() => {
  fetchStudents();
});
</script>

<style scoped>
/* 作业发布容器样式 */
.task-upload-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

/* 选择按钮组样式 */
.selection-buttons {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

/* 按钮间隔样式 */
.el-button + .el-button {
  margin-left: 10px;
}

/* 学生卡片和组卡片容器样式 */
.student-cards, .group-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  width: 100%;
}

/* 学生卡片和组卡片样式 */
.student-card, .group-card {
  width: calc(25% - 12px);
  cursor: pointer;
  position: relative;
  box-sizing: border-box;
  padding: 16px;
  border: 1px solid #ebebeb;
  border-radius: 8px;
  transition: all 0.3s;
}

/* 卡片悬停效果 */
.student-card:hover, .group-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 选中卡片样式 */
.selected-card {
  border: 2px solid #409eff;
  background-color: #f5f7fa;
}

/* 学生信息和组信息样式 */
.student-info, .group-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 头像样式 */
.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-bottom: 8px;
}

/* 详细信息样式 */
.details, .group-details {
  text-align: center;
}

/* 详细信息段落样式 */
.details p, .group-details p {
  margin: 4px 0;
}

/* 选中图标样式 */
.selected-icon {
  position: absolute;
  top: 10px;
  right: 10px;
  color: green;
  font-size: 24px;
}

/* 已选学生标签样式 */
.selected-student-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

/* 已选组标签样式 */
.selected-group-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

/* 弹窗底部样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 20px 0 0;
}

/* 自定义样式：对齐选择学生按钮和文件上传框 */
.el-form-item {
  margin-bottom: 15px;
}

.selection-buttons {
  margin-bottom: 15px;
}

.upload-demo {
  margin-bottom: 15px;
}
</style>
